import crypto from 'crypto';

/**
 * 从JWK格式导入AES密钥
 * @param jwkString JWK格式的密钥字符串
 * @returns CryptoKey对象
 */
export const importKeyFromJWK = async (jwkString: string): Promise<CryptoKey> => {
  const jwk = JSON.parse(jwkString);
  return await crypto.subtle.importKey(
    'jwk',
    jwk,
    {
      name: 'AES-GCM',
      length: 256,
    },
    true,
    ['decrypt']
  );
};

/**
 * 解密数据
 * @param encryptedData Base64编码的加密数据
 * @param iv Base64编码的初始化向量
 * @param key CryptoKey对象
 * @returns 解密后的字符串
 */
export const decryptData = async (
  encryptedData: string,
  iv: string,
  key: CryptoKey
): Promise<string> => {
  const encryptedBuffer = Buffer.from(encryptedData, 'base64');
  const ivBuffer = Buffer.from(iv, 'base64');

  const decrypted = await crypto.subtle.decrypt(
    {
      name: 'AES-GCM',
      iv: ivBuffer,
    },
    key,
    encryptedBuffer
  );

  return new TextDecoder().decode(decrypted);
};
